package com.watson.nettydemo.demo09;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ScheduledFuture;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author AdminWatson
 * @date: 2022/3/11 15:19
 * @version: 1.0
 */
public class WebSocketClientHandler extends ChannelInboundHandlerAdapter {
    private GenericFutureListener listener;
    private ScheduledFuture<?> schedule;
    private Bootstrap bootstrap;

    public WebSocketClientHandler(Bootstrap bootstrap) {
        this.bootstrap = bootstrap;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 发送心跳
        sendHeartbeat(channel);
    }

    private void sendHeartbeat(Channel channel) {
        //生成一个[1，8)的随机数作为心跳发送的时间间隔
        int interval = new Random().nextInt(7) + 1;
        schedule = channel.eventLoop().schedule(() -> {
            // 如果是激活状态
            if (channel.isActive()) {
                System.out.println("向server发送心跳");
                channel.writeAndFlush("~PING~");
            } else {
                System.out.println("与server的连接已经关闭");
            }
        }, interval, TimeUnit.SECONDS);


        listener = (future -> {
            // 再次发送心跳
            sendHeartbeat(channel);
        });
        // 向定时器添加监听
        schedule.addListener(listener);


    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 一旦连接关闭，将监听器移除，就不会咋递归执行了，防止栈溢出
        schedule.removeListener(listener);

        System.out.println("尝试重新连接。。。");
        //重新连接
        bootstrap.connect("localhost", 6666).sync();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
